<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="协议名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入协议名称"
          clearable
          maxlength="200"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="协议地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入协议地址"
          clearable
          maxlength="200"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shop:protocol:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['shop:protocol:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shop:protocol:remove']"
        >删除</el-button>
      </el-col>
      <!--
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['shop:goodsspec:export']"
        >导出</el-button>
      </el-col>
      -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="tables" v-loading="loading" :data="tableList" @selection-change="handleSelectionChange" :default-sort="defaultSort" @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="ID" align="center" prop="id" />-->
      <el-table-column label="协议名称" align="center" prop="name" />
      <el-table-column label="协议地址" align="center" prop="address" />
      <el-table-column label="是否绑定商品" align="center" prop="isBind">
        <template slot-scope="scope">
          <span>{{ scope.row.isBind?'是':'否' }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="创建时间" align="center" prop="createDate" width="180" sortable="custom" :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shop:protocol:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shop:protocol:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" @submit.native.prevent>
        <el-form-item label="协议名称" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入协议名称" maxlength="50"/>
        </el-form-item>
        <el-form-item label="协议地址" prop="address">
          <el-input v-model.trim="form.address" placeholder="请输入协议地址"/>
        </el-form-item>
        <!--<el-form-item label="协议类型" prop="protocolType">
          <el-select style="width: 100%" v-model="form.protocolType" placeholder="请输入协议类型">
            <el-option v-for="item in protocolTypeArr" :key="item.value" :value="item.value" :label="item.label"/>
          </el-select>
        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" class="inputClass" placeholder="请输入备注" maxlength="300" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Cookies from "js-cookie";
  import { getDicts } from "@/api/system/dict/data";
  import { list, get, del, add, update } from "@/api/shop/protocol";

  export default {
    name: "Protocol",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格数据
        tableList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 日期范围
        dateRange: [],
        // 默认排序
        defaultSort: {prop: 'createDate', order: 'descending'},
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: undefined,
          address: undefined,
          orderByColumn: 'createDate',
          isAsc: 'descending',
          isSpuSide:false
        },
        // 表单参数
        form: {
          id: undefined,
          name: undefined,
          address: undefined,
          // protocolType: undefined,
          remark: undefined,
        },
        selectedRow:null,
        // 表单校验
        rules: {
          name: [
            { required: true, message: "协议名称不能为空", trigger: "blur" },
            {
              min: 1,
              max: 20,
              message: "格式错误：20个汉字以内",
              trigger: "blur",
            }
          ],
          address: [
            { required: true, message: "协议地址不能为空", trigger: "blur" },
            {
              pattern: /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/,
              message: "格式错误：地址以http开头",
              trigger: "blur"
            }
          ],
          // protocolType: [
          //   { required: true,pattern:/^[0-9]+$/, message: "请选择协议类型", trigger: "blur" },
          // ],
        },
        // protocolTypeArr: [],
      };
    },
    created() {
      this.getList();
      // this.getDictsFun();
    },
    methods: {
      // getDictsFun(){
      //   getDicts('protocol_type').then(response => {
      //     this.protocolTypeArr = [];
      //     response.data.forEach((item)=>{
      //       this.protocolTypeArr.push({
      //         label: item.dictLabel,
      //         value: Number(item.dictValue),
      //       });
      //     })
      //   })
      // },
      /** 查询规格列表 */
      getList() {
        this.loading = true;
        list(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
            this.tableList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          address: undefined,
          name: undefined,
          // protocolType: undefined,
          remark: undefined,
        };
        this.resetForm("form");
        this.selectedRow = null;
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.$refs.tables.sort(this.defaultSort.prop, this.defaultSort.order);
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加协议";
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 排序触发事件 */
      handleSortChange(column, prop, order) {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
        this.getList();
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.selectedRow = row;
        const id = row.id || this.ids
        get(id).then(response => {
          this.form.id = response.data.id||''
          this.form.name = response.data.name||''
          this.form.address = response.data.address||''
          // this.form.protocolType = Number(response.data.protocolType)
          this.form.remark = response.data.remark||''
          // this.form = response.data;
          this.open = true;
          this.title = "修改协议";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              update(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              const username = Cookies.get("username");
              this.form.createBy = username;
              add(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id ? [row.id] : this.ids;
        let tempArr = []
        this.tableList.forEach(e=>{
          if (ids.includes(e.id)) {
            tempArr.push(e.name)
          }
        })
        let txt = `是否确认删除协议名称为 （` + tempArr.join('，') + `） 的数据项？`;
        let confirmText = [txt];
        const  newDatas = [];
        const h = this.$createElement;
        if(row.isBind){
          confirmText.push(`该协议已经被商品使用且已经上架，新建商品无法选择已删除的协议，已使用该协议且处于上架状态的商品不受影响。`);
        }
        for (const i in confirmText) {
          newDatas.push(h('p', null, confirmText[i]))
        }

        this.$modal
          .confirm(
            h('div', null, newDatas),
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(function() {
            return del(ids);
          })
          .then(() => {
            this.handleQuery();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {})
      },
    }
  };
</script>
<style scoped>
  /* element-ui input style overload */
  ::v-deep .inputClass > textarea {
    padding-right: 40px;
  }
</style>
